<?php

namespace App\Http\Controllers\Caiwu;

use App\Http\Controllers\Controller;
use App\Models\Channel;
use App\Models\Customer;
use App\Models\Department;
use App\Models\Finance;
use App\Models\Node;
use App\Models\Order;
use App\Models\OrderRemark;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\View;

class OrderController extends Controller
{
    /**
     * 订单列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        if ($request->ajax()){
            $user = $request->user();
            $data = $request->all([
                'customer_id',
                'num',
            ]);
            $res = Order::query()
                ->with('customer')
                ->where(function ($q) use($user){
                    if ($user->hasPermissionTo('caiwu.order.list_all')) {

                    } elseif ($user->hasPermissionTo('caiwu.order.list_department_sub')) {
                        $departmentIds = Department::query()->where('parent_id',$user->department_id)->pluck('id')->toArray();
                        $departmentIds = array_merge($departmentIds,[$user->department_id]);
                        return $q->whereIn('owner_department_id', $departmentIds);
                    } elseif ($user->hasPermissionTo('caiwu.order.list_department')) {
                        return $q->where('owner_department_id',$user->department_id);
                    }else{
                        return $q->where('owner_user_id',$user->id)->orWhere('accept_user_id',$user->id);
                    }
                })
                ->when($data['customer_id'], function ($query) use ($data) {
                    return $query->where('customer_id', $data['customer_id']);
                })
                ->when($data['num'], function ($query) use ($data) {
                    return $query->where('num', $data['num']);
                })
                ->orderByDesc('id')
                ->paginate($request->get('limit', 30));
            return $this->success('ok',$res->items(),$res->total());
        }
        return View::make('caiwu.order.index');
    }

    public function create(Request $request)
    {
        return View::make('caiwu.order.create');
    }

    public function store(Request $request)
    {
        $data = $request->all([
            'customer_id',
            'stime',
            'etime',
            'total_money',
            'payed_money',
            'multiple_file',
            'remark',
            'pay_type',
            'first_money',
            'mid_money',
            'last_money',
            'product_ids',
        ]);
        $customer = Customer::query()->where('id',$data['customer_id'])->first();
        if ($customer == null){
            return $this->error('请选择客户');
        }
        try {
            $data = array_merge($data,[
                'num' => create_num('dd'),
                'owner_department_id' => $request->user()->department_id,
                'owner_user_id' => $request->user()->id,
                'owner_user_nickname' => $request->user()->nickname,
            ]);
            Order::create($data);
            return $this->success('操作成功，请等待管理员审核');
        }catch (\Exception $exception){
            Log::error('生成订单异常:'.$exception->getMessage());
            return $this->error();
        }
    }


    public function edit(Request $request,$id)
    {
        $model = Order::query()->with('customer')->find($id);
        return View::make('caiwu.order.edit',compact('model'));
    }

    public function update(Request $request,$id)
    {
        $model = Order::query()->with('customer')->find($id);
        $data = $request->all([
            'stime',
            'etime',
            'total_money',
            'payed_money',
            'multiple_file',
            'remark',
            'pay_type',
            'contract_file',
            'first_money',
            'mid_money',
            'last_money',
            'product_ids',
        ]);
        try {
            // 更新后订单需要重新审核，不论数据是否有变动
            $data = array_merge($data,[
                'check_status' => 1,
                'check_result' => null,
                'check_time' => null,
                'check_user_id' => 0,
                'check_user_nickname' => null,
            ]);
            $model->update($data);
            return $this->success('操作成功，请等待管理员审核');
        }catch (\Exception $exception){
            Log::error('更新订单异常:'.$exception->getMessage());
            return $this->error();
        }
    }


    /**
     * 审核
     * @param Request $request
     * @return \Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function check(Request $request)
    {
        $model = Order::query()->find($request->input('id'));
        if ($request->ajax()){
            try {
                $data = $request->all(['check_status','check_result']);
                if ($data['check_status']==null){
                    return $this->error('请选择状态');
                }
                $data = array_merge($data,[
                    'check_time' => date('Y-m-d H:i:s'),
                    'check_user_id' => $request->user()->id,
                    'check_user_nickname' => $request->user()->nickname,
                ]);
                $model->update($data);
                return $this->success();
            }catch (\Exception $exception){
                Log::error('订单审核异常：'.$exception->getMessage());
                return $this->error();
            }
        }
        return View::make('caiwu.order.check',compact('model'));
    }

    /**
     * 收款
     * @param Request $request
     * @return \Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function pay(Request $request)
    {
        $model = Order::query()->find($request->input('id'));
        if ($request->ajax()){
            try {
                if ($model->check_status!=3){
                    return $this->error('订单未审核通过，禁止收款');
                }
                $data = $request->all([
                    'money',
                    'pay_type',
                    'remark',
                    'multiple_file',
                ]);
                $data = array_merge($data,[
                    'num' => $model->num,
                    'customer_id' => $model->customer_id,
                    'order_id' => $model->id,
                    'owner_department_id' => $request->user()->department_id,
                    'owner_user_id' => $request->user()->id,
                    'owner_user_nickname' => $request->user()->nickname,
                ]);
                Finance::create($data);
                return $this->success('操作成功，等待管理员审核');
            }catch (\Exception $exception){
                Log::error('订单收款异常：'.$exception->getMessage());
                return $this->error();
            }
        }
        return View::make('caiwu.order.pay',compact('model'));
    }


    /**
     * 订单分配
     * @param Request $request
     * @return \Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function assignment(Request $request)
    {
        $orderId = $request->input('order_id');
        $model = Order::query()->find($orderId);
        if ($request->ajax()){
            if ($model->check_status!=3){
                return $this->error('订单未审核通过，禁止分配');
            }
            $data = $request->all(['user_id']);
            $user = User::query()->find($data['user_id']);
            if ($user == null){
                return $this->error('请选择接单用户');
            }
            try {
                Order::query()
                    ->where('id',$orderId)
                    ->update([
                        'send_time' => date('Y-m-d H:i:s'),
                        'send_user_nickname' => $request->user()->nickname,
                        'send_user_id' => $request->user()->id,
                        'send_department_id' => $request->user()->department_id,

                        'accept_time' => date('Y-m-d H:i:s'),
                        'accept_user_nickname' => $user->nickname,
                        'accept_user_id' => $user->id,
                        'accept_department_id' => $user->department_id,
                    ]);
                return $this->success();
            }catch (\Exception $exception){
                Log::error('订单分配异常：'.$exception->getMessage());
                return $this->error();
            }
        }
        return View::make('caiwu.order.assignment',compact('model'));
    }

    /**
     * 删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Request $request)
    {
        $ids = $request->input('ids');
        try {
            Order::query()->whereIn('id', $ids)->delete();
            return $this->success();
        } catch (\Exception $exception) {
            Log::error('删除订单异常：' . $exception->getMessage());
            return $this->error();
        }
    }

    /**
     * 跟进备注订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function remarkStore(Request $request)
    {
        $model = Order::query()->find($request->input('id'));
        if ($model->check_status!=3){
            return $this->error('订单未审核通过，禁止生产');
        }
        $nodes = Node::query()
            ->whereIn('type',[1,3])
            ->orderBy('sort','asc')
            ->pluck('name','id')
            ->toArray();
        $data = $request->all(['node_id','content','multiple_file']);
        $data['node_name'] = Arr::get($nodes,$data['node_id'],null);
        try {
            OrderRemark::create([
                'order_id' => $model->id,
                'node_id' => $data['node_id'],
                'node_name' => $data['node_name'],
                'content' => $data['content'],
                'multiple_file' => $data['multiple_file'],
                'user_id' => $request->user()->id,
                'user_nickname' => $request->user()->nickname,
            ]);
            return $this->success('跟进成功，等待管理员审核');
        }catch (\Exception $exception){
            Log::error('跟进订单异常：'.$exception->getMessage());
            return $this->error();
        }
    }


    /**
     * 跟进备注列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function remarkList(Request $request)
    {
        $model = Order::query()->find($request->input('id'));
        if ($request->ajax()){
            $res = OrderRemark::query()
                ->where('order_id',$model->id)
                ->orderByDesc('id')
                ->paginate($request->get('limit', 30));
            return $this->success('ok',$res->items(),$res->total());
        }
        $nodes = Node::query()->whereIn('type',[1,3])->orderBy('sort','asc')->get();
        $steps = OrderRemark::query()
            ->where('order_id',$model->id)
            ->where('check_status',3)
            ->pluck('node_id')
            ->toArray();
        $step = 0;
        foreach ($nodes as $node){
            if (in_array($node->id,$steps)){
                $step += 1;
            }
        }
        return View::make('caiwu.order.remark_list',compact('model','nodes','step'));
    }

    /**
     * 跟进审核
     * @param Request $request
     * @return \Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function remarkCheck(Request $request)
    {
        $model = OrderRemark::query()->find($request->input('id'));
        if ($request->ajax()){
            DB::beginTransaction();
            try {
                $data = $request->all(['check_status','check_result']);
                if ($data['check_status']==null){
                    return $this->error('请选择状态');
                }
                $data = array_merge($data,[
                    'check_time' => date('Y-m-d H:i:s'),
                    'check_user_id' => $request->user()->id,
                    'check_user_nickname' => $request->user()->nickname,
                ]);
                if ($data['check_status']==3){
                    Order::query()
                        ->where('id',$model->order_id)
                        ->update([
                            'node_id' => $model->node_id,
                            'node_name' => $model->node_name,
                        ]);
                }
                $model->update($data);
                DB::commit();
                return $this->success();
            }catch (\Exception $exception){
                DB::rollBack();
                Log::error('订单备注审核异常：'.$exception->getMessage());
                return $this->error();
            }
        }
        return View::make('caiwu.order.remark_check',compact('model'));
    }

}
